﻿using JsonRpcService.Contract;
using StreamJsonRpc;
using System.Net.WebSockets;

namespace WebSocketSample.Client;

class Program
{
    static async Task Main(string[] args)
    {
        Console.WriteLine("正在与服务端建立连接...");
        using var webSocket = new ClientWebSocket();
        var uri = new Uri("ws://localhost:5000/rpc/greeter");
        await webSocket.ConnectAsync(uri, CancellationToken.None);
        Console.WriteLine("已建立连接");

        var messageHandler = new WebSocketMessageHandler(webSocket);
        var greeterService = JsonRpc.Attach<IGreeterService>(messageHandler);

        Console.Write("请输入你的姓名：");
        var name = Console.ReadLine() ?? "json-rpc";
        var request = new HelloRequest { Name = name };
        Console.WriteLine("开始向服务端发送消息...");
        var response = await greeterService.SayHelloAsync(request);
        Console.WriteLine($"收到来自服务端的响应：{response.Message}");

        Console.WriteLine("正在断开连接...");
        await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "断开连接", CancellationToken.None);
        Console.WriteLine("已断开连接");

        Console.ReadKey();
    }
}
